package fei.yuzhi.com.loveflowers.fragment.firstpagefragment.search;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import butterknife.BindView;
import butterknife.ButterKnife;
import fei.yuzhi.com.loveflowers.R;
import fei.yuzhi.com.loveflowers.fragment.firstpagefragment.searchresult.SearchResultActivity;
import fei.yuzhi.com.loveflowers.utils.MyListView;

/**
 * Created by My on 2016/10/15.
 */
public class SearchActivity extends AppCompatActivity {
    @BindView(R.id.firstpage_search_et)
    EditText firstpageSearchEt;//输入框
    @BindView(R.id.firstpage_search_search)
    TextView firstpageSearchSearch;//搜索按钮
    @BindView(R.id.firstpage_search_tip)
    TextView firstpageSearchTip;//搜索历史
    @BindView(R.id.firstpage_search_clear)
    TextView firstpageSearchClear;//清空搜索历史
    @BindView(R.id.firstpage_search_listView)
    MyListView firstpageSearchListView;//展示搜索记录的listview
    @BindView(R.id.firstpage_search_back)
    ImageView firstpageSearchBack;

    private SQLiteDatabase db;
    private RecordSQLiteOpenHelper helper = new RecordSQLiteOpenHelper(this);
    private BaseAdapter adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);

        //返回按钮的点击事件
        firstpageSearchBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        //清除搜索历史
        firstpageSearchClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteData();
                queryData("");
            }
        });
        //搜索框的键盘搜索键点击回调
        firstpageSearchEt.setOnKeyListener(new View.OnKeyListener() {//输入完成后按键盘上的搜索键
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                //修改回车键功能
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent
                        .ACTION_DOWN) {
                    onSearchClick();
                }
                return false;
            }
        });
        //搜索框旁边的搜索按钮点击回调
        firstpageSearchSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onSearchClick();
            }
        });

        //搜索框的文本变化实时监听
        firstpageSearchEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().trim().length() == 0) {
                    firstpageSearchTip.setText("搜索历史");
                } else {
                    firstpageSearchTip.setText("搜索结果");
                }

                String tempName = firstpageSearchEt.getText().toString();
                //根据tempName去模糊查询数据库中有没有数据
                queryData(tempName);
            }
        });

        firstpageSearchListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView textView = (TextView) view.findViewById(android.R.id.text1);
                String name = textView.getText().toString();
                firstpageSearchEt.setText(name);
                //获取到item上的字，根据该关键字跳转到另外的页面
                Intent intent = new Intent(SearchActivity.this, SearchResultActivity.class);
                intent.putExtra("keyword", name);
                startActivity(intent);
            }
        });

        // 在activity中执行，第一次进入查询所有的历史记录
        queryData("");
    }

    //点击搜索时执行的操作
    public void onSearchClick() {
        //先隐藏键盘
        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        //按完搜索键后将当前查询的关键字保存起来，如果该关键字已经存在就不执行保存
        boolean hasData = hasData(firstpageSearchEt.getText().toString().trim());
        if (!hasData) {
            insertData(firstpageSearchEt.getText().toString().trim());
            queryData("");
        }
        //根据输入的内容模糊查询商品，并跳转到响应的页面
        String keyword = firstpageSearchEt.getText().toString().trim();
        Intent intent = new Intent(SearchActivity.this, SearchResultActivity.class);
        intent.putExtra("keyword", keyword);
        startActivity(intent);
    }

    //插入数据
    public void insertData(String tempName) {
        db = helper.getWritableDatabase();
        db.execSQL("insert into searching(name) values('" + tempName + "')");
        db.close();
    }

    //模糊查询数据
    public void queryData(String tempName) {
        Cursor cursor = helper.getReadableDatabase().rawQuery
                ("select id as _id,name from searching where name like '%" + tempName + "%' order" +
                        " by id desc ", null);
        //创建adapter适配器对象
        adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, new
                String[]{"name"},
                new int[]{android.R.id.text1}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        //设置适配器
        firstpageSearchListView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    //检查数据库中是否已经有该条数据了
    public boolean hasData(String tempName) {
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from searching where name =?", new String[]{tempName});
        //判断是否有下一个
        return cursor.moveToNext();
    }

    //清空数据
    public void deleteData() {
        db = helper.getWritableDatabase();
        db.execSQL("delete from searching");
        db.close();
    }
}
